layui.use(['form','layer','jquery','laypage','laytpl'],function(){
	var form = layui.form,
		layer = parent.layer === undefined ? layui.layer : parent.layer,
        layPage = layui.laypage,
		$ = layui.jquery,
        laytpl = layui.laytpl;

    //校验登录状态
    if(isNotLogIn()){
        return;
    }
	var managerId = getCookie("managerId");
	var count= 0;
	//管理员信息模板
    var managerTpl = "{{# layui.each(d.data, function(index, item){ }}<tr itemid=\"{{item.manager_id}}\"><td><input type=\"checkbox\" name=\"checked\" lay-skin=\"primary\" lay-filter=\"choose\"></td><td>{{item.real_name}}</td><td>{{item.email}}</td><td>{{item.sex}}</td><td>{{item.manager_level}}</td><td>{{item.telephone}}</td><td>{{item.job_post}}</td><td><form class='layui-form' action=''><div class='layui-input-block'><input {{# if ( '1'==item.valid_tag){ }} checked= 'true' {{# } }} name='open' lay-skin='switch' lay-filter='isValid' lay-text='正常|冻结' type='checkbox'></div></form></td><td>{{item.last_login_time}}</td><td><button class='layui-btn layui-btn-sm layui-btn-danger delete-btn'><i class='layui-icon'>&#xe640;</i></button></td></tr>{{# }); }}";
    getManagerInfo();


    //获取管理员信息
    function getManagerInfo(page,limit){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        page = isNull(page)?0:page;
        limit = isNull(limit)?10:limit;
        var index = layer.load(3);
        //清空当前数据
        $(".users_content").html("");
        $.ajax({
            url:"/CivilAffairs/manager/getManagerInfo",
            type : "post",
            data : {"page":page,"limit":limit},
            async : false,
            dataType : "json",
            success : function(result) {
                layer.close(index);
                if(checkResult(result)){
                    laytpl(managerTpl).render(result.data.data, function(html) {
                        $(".users_content").html(html);
                    });
                    //重新渲染
                    form.render('checkbox');
                    //需要重新加载分页
                    if(count!=result.data.count){
                        count = result.data.count;
                        //分页组件
                        layPage.render({
                            elem: 'news-page'
                            ,count: result.data.count //数据总数，从服务端得到
                            ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                            ,jump: function(obj, first){
                                //首次不执行
                                if(!first){
                                    console.log("not first");
                                    getManagerInfo(obj.curr,obj.limit);
                                }
                            }
                        });
                    }
                }
            },
            error : function(result) {
                layer.close(index);
                reqError(result,"获取管理员信息异常");
            }
        });
    }

    //信息内容有效与否的切换
    form.on('switch(isValid)', function(data){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var optManagerId = getCookie("managerId");
        if(isNull(optManagerId)){
            layer.msg("登录状态已失效，请重新登录");
            logOut(true,true);
            return;
        }
        var isValid = this.checked ?"1":"0";
        var _this = $(this);
        var managerId = $(this).parents("tr").attr("itemid");
        var index = layer.load(3);
        $.ajax({
            url:"/CivilAffairs/manager/changeValidTag",
            type:"post",
            data:{"isValid":isValid,"dataId":managerId,"dataType":"Manager","optManagerId":optManagerId},
            dataType:"json",
            success:function(result){
                layer.close(index);
                if(checkResult(result)){
                    layer.msg(result.detail,{icon:6});
                }else{
                    //切换生效失败
                    if("1"==isValid){
                        _this.removeAttr("checked");
                    }else{
                        _this.prop("checked",'checked');
                    }
                    form.render("checkbox");
                }
            },
            error : function(result) {
                layer.close(index);
                console.log((this.checked?"展示":"不展示")+"管理员信息:"+result.status+","+result.statusMessage+",newsId:"+newsId);
                layer.msg("切换信息展示标识异常,请稍后重试",{icon:2});
            }
        });

    });

    //全选
    form.on('checkbox(selectAll)', function(data){
        var child = $(data.elem).parents('table').find('tbody input[name="checked"]:not([name="open"])');
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //删除
    $("body").on("click",".delete-btn",function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var _this = $(this);
        layer.confirm('确定删除此信息？',{icon:3, title:'提示信息'},function(index){
            var managerId = _this.parents("tr").attr("itemid");
            deleteManager(managerId);
            layer.close(index);
        });
    });



    //删除信息
    function deleteManager(managerId,isAllDel){
        if(isNull(managerId)){
            return;
        }
        var optManagerId = getCookie("managerId");
        if(isNull(optManagerId)){
            layer.msg("请先重新登录");
            logOut(true,true);
            return;
        }
        $.ajax({
            url : "/CivilAffairs/manager/deleteManager",
            type : "post",
            data : {"managerId":managerId,"optManager":optManagerId},
            async : false,
            dataType : "json",
            success : function(result) {
                if(checkResult(result) && !isAllDel){
                    getManagerInfo(0,10);
                }
            },
            error:function(result){
                reqError(result,"删除信息异常");
            }
        });
    }

    //批量删除
    $(".batchDel").click(function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var $checkbox = $('.users_content tr input[name="checked"]');
        var $checked = $('.users_content tr input[name="checked"]:checked');
        if($checkbox.is(":checked")){
            layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
                var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                //删除数据
                $checked.each(function(){
                    var managerId = $(this).parents("tr").attr("itemid");
                    deleteManager(managerId,true);
                });
                getManagerInfo(0,10);
                layer.close(index);
                layer.msg("删除成功",{icon:6});
            });
        }else{
            layer.msg("请选择需要删除的信息");
        }
    });

	//添加管理员
	$(".usersAdd_btn").click(function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
		var index = layui.layer.open({
			title : "添加管理员",
			type : 2,
			content : "addUser.html",
			success : function(layero, index){
				setTimeout(function(){
					layui.layer.tips('点击此处返回管理员列表', '.layui-layer-setwin .layui-layer-close', {
						tips: 3
					});
				},500)
			}
		});
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        });
        layui.layer.full(index);
	});

    var searchCount = 0;
    var managerName = "";
    //搜索
    $(".search_btn").click(function () {
        var searchName = $(".search_input").val();
        if(isNull(searchName)){
            layer.msg("请输入要搜索的管理员姓名");
            return;
        }
        searchNameInfo(searchName);
    });

    //判断回车
    $(document).keyup(function (e) {//捕获文档对象的按键弹起事件
        if (e.keyCode == 13) {
            $(".search_btn").click();
        }
    });

    function searchNameInfo(searchName,page,limit){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        page = isNull(page)?0:page;
        limit = isNull(limit)?10:limit;
        var index = layer.load(3);
        $.ajax({
            url : "/CivilAffairs/manager/getManagerInfo",
            type : "post",
            data : {"searchName":searchName,"page":page,"limit":limit},
            async : false,
            dataType : "json",
            success : function(result) {
                layer.close(index);
                layer.msg(result.detail,{icon:6});
                if("0000"==result.status){
                    laytpl(managerTpl).render(result.data.data, function(html) {
                        $(".users_content").html(html);
                    });
                    //重新渲染
                    form.render('checkbox');
                    //需要重新加载分页
                    if(searchCount!=result.data.count || name != searchName){
                        searchCount = result.data.count;
                        managerName = searchName;
                        //分页组件
                        layPage.render({
                            elem: 'news-page'
                            ,count: result.data.count //数据总数，从服务端得到
                            ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                            ,jump: function(obj, first){
                                //首次不执行
                                if(!first){
                                    searchNameInfo(searchName,obj.curr,obj.limit);
                                }
                            }
                        });
                    }
                }else{
                    layer.msg("未查询到管理员[ "+searchName+" ]的信息",{icon:2});
                }

            },
            error:function(result){
                layer.close(index);
                reqError(result,"搜索管理员信息异常");
            }
        });
    }

	//通过判断文章是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="open"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="open"]):checked')
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#selectAll').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#selectAll').get(0).checked = false;
		}
		form.render('checkbox');
	});

        
});